class AutenticateController {
	def mailService
	
    def index = { redirect(action:show,params:params) }

    def show = { 
		render(view:'login') 
    }

    def login = {
        if (params?.alias && params?.password) {
        	def userInstance = User.findWhere(alias:params.alias, password:params.password)
        	
        	if (userInstance != null) { 
        		//log.debug "user ${userInstance.alias} logged"
        		flash.message = "wellcome.user"
                flash.args = [userInstance.id]
        		flash.defaultMessage="WELLCOME ${userInstance.alias}"
        		session['user'] = userInstance
        		redirect(controller:"note", action:"list")
        		return
        	}
        }        	
    
        def user = new User()
		user.errors.rejectValue("alias", "reminder.password.no.alias", null, "INTRODUZCA UN ALIAS Y PASSWORD CORRECTOS")
		user.errors.rejectValue("password", "", null, "")
        render(view: "login", model: [userInstance:user])
    }

    def cancel = {
    	println "BACK"
		redirect(controller:"note", action:"list")
    }

    def logout = {
		session.invalidate()
		redirect(controller:"note", action:"list")
	}
    
    
    def reminderPassword = {
		def user = User.findByAlias(params.alias)
		if (user) {
			try {
				mailService.sendMail {     
				  to user.email
				  subject "tu password"
				  body user.password
				  //"your.password.subject"
				  //'your.password.begin' + user.password + 'your.password.end' 
				}
				flash.message = "password.send"
        		flash.defaultMessage="SE HA ENVIADO SU PASSWORD A SU DIRECCION DE CORREO"
        		redirect(controller:"note", action:"list")
				
			} catch (e) {
				log.error e
				user = new User()
				user.errors.rejectValue("alias", "tecnic.problem", null, "PROBLEMAS TECNICOS")
				render(view: "login", model: [userInstance:user])
			}
		} else {
			//user = new User()
			user.errors.rejectValue("alias", "reminder.password.no.alias", null, "INTRODUZCA UN ALIAS CORRECTO")
			render(view: "login", model: [userInstance:user])
		}
	}
}